package com.example.payment.controller;

import com.alipay.api.AlipayApiException;
import com.example.core.annotation.HasPerm;
import com.example.model.check_in.CheckIn;
import com.example.model.response.Result;
import com.example.model.payment.Payment;
import com.example.payment.service.PaymentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @PutMapping
    public Result insert(@RequestBody Payment payment) {
        return Result.success(paymentService.insert(payment) > 0 ? "成功":"失败");
    }

    @GetMapping("/list")
    @HasPerm("accommodation:payment:list")
    public Result list() {
        List<Payment> list = paymentService.list(null);
        return Result.success(list);
    }

    @HasPerm("accommodation:payment:list")
    @GetMapping("/page")
    public Result list(@RequestParam("pageNum")int pageNum, @RequestParam("pageSize")int pageSize, Payment payment) {
        Page<Payment> page = PageHelper.startPage(pageNum, pageSize);
        List<Payment> list = paymentService.list(payment);
        PageInfo<Payment> pageInfo = new PageInfo<>(page);
        return Result.success(pageInfo);
    }
//    @PostMapping("/pay")
//    public Result makePayment(@RequestBody CheckIn checkIn) {
//        return Result.success(paymentService.makePayment(checkIn));
//    }

    @PostMapping("/pay")
    public Result makePayment(@RequestBody Payment payment,
                              @RequestParam("amount") BigDecimal amount,
                              @RequestParam("pay") BigDecimal pay) {
        return Result.success(paymentService.makePayment(payment, amount, pay));
    }

    @PostMapping("/notify")
    public String notify(@RequestBody String notify) {
        paymentService.analysis(notify);
        return "success";
    }

    @PostMapping("/research")
    public Result research(@RequestParam("paymentId") Long paymentId) {
        return Result.success(paymentService.research(paymentId));
    }

    @HasPerm("accommodation:payment:get")
    @GetMapping("/{paymentId}")
    public Result get(@PathVariable("paymentId") Long paymentId) {
        return Result.success(paymentService.get(paymentId));
    }

    @PostMapping("/refund")
    public Result refund(@RequestParam("paymentId") Long paymentId, @RequestParam("amount") BigDecimal amount) {
        try {
            paymentService.refund(paymentId, amount);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return Result.success("退款成功");
    }

}
